package com.itcast.mallweb.service.impl;

import com.itcast.admin.dto.RiderDTO;
import com.itcast.admin.entity.Rider;
import com.itcast.applet.entity.Order;
import com.itcast.applet.entity.RiderTask;
import com.itcast.mallweb.mapper.OrderMapper;
import com.itcast.mallweb.mapper.RiderMapper;
import com.itcast.mallweb.service.RiderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class RiderServiceImpl implements RiderService{
    @Autowired
    private RiderMapper riderMapper;

    @Autowired
    private OrderMapper orderMapper;

    //新增骑手
    public void addRider(RiderDTO rdiderDTO) {
        Rider rider = new Rider();
        rider.setStatus(0);
        BeanUtils.copyProperties(rdiderDTO, rider);
        riderMapper.addRider(rider);
    }

    //查询单个骑手
    public Rider getById(Long id) {
        Rider rider = riderMapper.getById(id);
        return rider;
    }

    //查询全部骑手
    public List<Rider> getRider() {
        List<Rider> riderList = riderMapper.getRiderList();
        return riderList;
    }

    //批量删除骑手
    public void deteleRider(List<Long> ids) {
        riderMapper.deteleRider(ids);
    }

    //骑手分配订单
    @Transactional
    public void addAllocation(com.itcast.applet.dto.RiderDTO riderDTO) {
        //先查订单的信息
        Order order = orderMapper.orderGetById(riderDTO.getOrderId());
        RiderTask riderTask = RiderTask.builder()
                .riderId(riderDTO.getRiderId())
                .orderId(order.getId())
                .addressId(order.getAddressId())
                .createTime(LocalDateTime.now())
                .build();
        //创建骑手任务表
        riderMapper.insetTask(riderTask);
        //修改骑手状态 0 - 1
        com.itcast.applet.entity.Rider rider = riderMapper.queryGetById(riderDTO.getRiderId());
        rider.setStatus(1);
        riderMapper.riderAmend(rider);

        //订单状态修改
        order.setStatus(2);
        order.setRiderId(riderDTO.getRiderId());
        orderMapper.orderAmend(order);
    }
}
